# coding:utf-8
import os
import hashlib
import traceback
import shutil
import requests
import conf
import global_
import time
import uuid
import logging

class BaiduClient(object):

    # 使用wgs84
    url = 'http://api.map.baidu.com/panorama/v2?ak={}&width=1024&height=512&location={},{}&fov=180&&coordtype=wgs84ll'
    ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'

    def __init__(self, ak, folder, stop_event=None):
        self.ak = ak
        self.folder = folder
        self.stop_event = stop_event

    def download_image(self, lat, lng):
        # 如果不重复才下载
        # 返回'ok'，表示下载成功
        # 返回'already'，表示之前就下载成功
        # 返回'retry'，表示由网络或其他原因引起的异常，需要重试
        # 返回'skip'，表示该地点不需要下载，需要跳过
        url = self.url.format(self.ak, lng, lat)
        m5 = hashlib.md5()
        try:
            r = requests.get(
                url,
                headers={'User-agent': self.ua},
                stream=True,
                timeout=60
            )
            r.raise_for_status()
            if r.headers['Content-Type'] == 'image/jpeg':
                tmp_filename = '/tmp/' + str(uuid.uuid1()) + '.jpg'
                with open(tmp_filename, 'wb') as f:
                    for chunk in r.iter_content(chunk_size=1024):
                        if chunk:  # filter out keep-alive new chunks
                            f.write(chunk)
                            f.flush()
                with open(tmp_filename, 'rb') as f:
                    m5.update(f.read())
                    filename = os.path.join(self.folder, str(m5.hexdigest()) + '.jpg')
                    if os.path.exists(filename):
                        os.remove(tmp_filename)
                        return 'already'
                try:
                    shutil.move(tmp_filename, filename)
                    self.last_filename = filename
                    return 'ok'
                except KeyboardInterrupt:
                    # 在移动过程中被中断，此时把不完全的文件删掉
                    if os.path.exists(filename):
                        os.remove(filename)
                    return 'retry'
            else:
                resp_data = r.json()
                status = resp_data['status']
                # 此处无街景
                if status == '402':
                    return 'skip'
                elif status == '302':
                    print("REACH MAXNUMBER, sleep")
                    time.sleep(30*60)
                    return "retry"
                else:
                    print('url:', url, 'result', resp_data)
                    return 'retry'
        except Exception:
            traceback.print_exc()
            return 'retry'

    def download(self):
        while global_.to_download_queue.empty() is False:
            item = global_.to_download_queue.get()
            time.sleep(0.5)
            ret = self.download_image(item['lat'], item['lng'])
            if ret == 'ok':
                logging.info('lat: {} lng: {} {}'.format(item['lat'], item['lng'], ret))
            else:
                logging.warning('lat: {} lng: {} {}'.format(item['lat'], item['lng'], ret))
            if ret == 'ok':
                item['path'] = self.last_filename
                global_.downloaded_queue.put(item)
            elif ret == 'already' or 'skip':
                pass
            elif ret == 'retry':
                global_.to_download_queue.put(item)
            else:
                pass
            if self.stop_event is not None and self.stop_event.is_set():
                print('now exiting...')
                break

if __name__ == '__main__':
    c = BaiduClient(conf.test_ak, 'data/sh')
    print(c.download_image(31.0003, 121.3))
